﻿/*
 Copyright © BlazeApps 2006.  All rights reserved.
 Visit www.BlazeApps.com for more information about us.
 */
using System;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace BA.Validators
{
	public class RadioButtonListRequiredFieldValidator : BaseValidator
	{
		protected override bool ControlPropertiesValid()
		{
			Control ctrl = FindControl(ControlToValidate);
			if (ctrl != null)
			{
				RadioButtonList _listctrl = (RadioButtonList)ctrl;
				return (_listctrl != null);
			}
			else
				return false;
		}

		protected override bool EvaluateIsValid()
		{
			return EvaluateIsChecked();
		}

		protected override void OnPreRender(EventArgs e)
		{
			base.OnPreRender(e);
			if (EnableClientScript)
			{
				this.ClientScript();
			}

		}

		private void ClientScript()
		{
			StringBuilder sb_Script = new StringBuilder();
			sb_Script.Append("<script language=\"javascript\">");
			sb_Script.Append("\r");
			sb_Script.Append("\r");
			sb_Script.Append("function verify_radiobutton(sender) {");
			sb_Script.Append("\r");
			sb_Script.Append("var val = document.getElementById(document.getElementById(sender.id).controltovalidate);");
			sb_Script.Append("\r");
			sb_Script.Append("var col = val.getElementsByTagName(\"*\");");
			sb_Script.Append("\r");
			sb_Script.Append("if ( col != null ) {");
			sb_Script.Append("\r");
			sb_Script.Append("for ( i = 0; i < col.length; i++ ) {");
			sb_Script.Append("\r");
			sb_Script.Append("if (col.item(i).tagName == \"INPUT\") {");
			sb_Script.Append("\r");
			sb_Script.Append("if ( col.item(i).checked ) {");
			sb_Script.Append("\r");
			sb_Script.Append("\r");
			sb_Script.Append("return true;");
			sb_Script.Append("\r");
			sb_Script.Append("}");
			sb_Script.Append("\r");
			sb_Script.Append("}");
			sb_Script.Append("\r");
			sb_Script.Append("}");
			sb_Script.Append("\r");
			sb_Script.Append("\r");
			sb_Script.Append("\r");
			sb_Script.Append("return false;");
			sb_Script.Append("\r");
			sb_Script.Append("}");
			sb_Script.Append("\r");
			sb_Script.Append("}");
			sb_Script.Append("\r");
			sb_Script.Append("</script>");
			Page.ClientScript.RegisterClientScriptBlock(GetType(), "CustomValidator_RadioButtonLists", sb_Script.ToString());
			Page.ClientScript.RegisterExpandoAttribute(ClientID, "evaluationfunction", "verify_radiobutton");
		}

		private bool EvaluateIsChecked()
		{
			RadioButtonList _rbl = ((RadioButtonList)FindControl(ControlToValidate));
			foreach (ListItem li in _rbl.Items)
			{
				if (li.Selected)
				{
					return true;
				}
			}
			return false;
		}
	}
}
